package com.gaoyi.websocket.controller;


import com.gaoyi.websocket.common.ResultUrl;
import com.gaoyi.websocket.common.ServerResponse;
import com.gaoyi.websocket.entity.TblNews;
import com.gaoyi.websocket.service.TblNewsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liaojunhui
 * @since 2021-03-19
 */
@RestController
@RequestMapping("/news")
@CrossOrigin
@Slf4j
public class TblNewsController {

    private static int code;
    private static int errno;

    /**
     * 时间格式化
     */
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");

    @Resource
    TblNewsService tblNewsService;


    /**
     * 图片保存路径，自动从yml文件中获取数据
     *   示例： E:/images/
     */
    @Value("${file-save-path}")
    private String fileSavePath;


    @RequestMapping("/save")
    public ServerResponse save(@RequestBody TblNews tblNews){
        LocalDateTime dateTime = LocalDateTime.now();
        tblNews.setCreateTime(dateTime);
        boolean flag = tblNewsService.save(tblNews);

        return flag? ServerResponse.success() : ServerResponse.error();
    }

    @RequestMapping("/query")
    public ServerResponse queryByTitle(String title, Integer id, @RequestParam(defaultValue = "1") int pageNo, @RequestParam(defaultValue = "10")int pageSize){

        if (title == null && id == null){

            PageHelper.startPage(pageNo,pageSize);

            List<TblNews> list = tblNewsService.getAllNews();

            PageInfo<TblNews> pageInfo = new PageInfo<TblNews>(list);

            return ServerResponse.successResponse(pageInfo);

        }else if (title != null && id == null){

            PageHelper.startPage(pageNo,pageSize);

            List<TblNews> list = tblNewsService.queryByStr(title);

            PageInfo<TblNews> pageInfo = new PageInfo<TblNews>(list);

            return ServerResponse.successResponse(pageInfo);
        }
            TblNews tblNews = tblNewsService.getById(id);

            return ServerResponse.successResponse(tblNews);

    }
    @RequestMapping("/delete/{id}")

    public ServerResponse deleteById(@PathVariable Integer id){

        boolean flag = tblNewsService.removeById(id);

        return flag ? ServerResponse.success() : ServerResponse.errorMessage("删除失败");

    }

    @RequestMapping("/update")
    public ServerResponse updateById(@RequestBody TblNews tblNews){
        LocalDateTime dateTime = LocalDateTime.now();
        tblNews.setCreateTime(dateTime);
        boolean flag = tblNewsService.updateById(tblNews);

        return flag ? ServerResponse.success() : ServerResponse.errorMessage("编辑失败");

    }


    /**
     * 查询上一条和下一条
     * */
    @RequestMapping("/upDown")
    public ServerResponse upDown(Integer num, Integer titleId){
        if (num == 1){
            TblNews tblNews = tblNewsService.nextNews(titleId);
            return ServerResponse.successResponse(tblNews);
        }
            TblNews tblNews = tblNewsService.preNews(titleId);
            return ServerResponse.successResponse(tblNews);

    }


    /**
     * 上传图片
     * */
    @RequestMapping("/upload")
    public ResultUrl uploadImg(MultipartFile file, HttpServletRequest request){

        String directory = simpleDateFormat.format(new Date());

        /**
         *  2.文件保存目录  usr/local/images
         *  如果目录不存在，则创建
         */
        File dir = new File(fileSavePath + directory);  //以时间为单位创建的多层目录
        if (!dir.exists()) {
            dir.mkdirs();
        }
        log.info("图片上传，保存的真实位置位置：" + fileSavePath + directory);
        /**
         * 3.给文件重新设置一个名字
         */
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "")+suffix;

        /**
         * 4.创建这个新文件
         */
        File newFile = new File(fileSavePath + directory + newFileName);

        /**
         * 4.创建这个新文件
         */
        try {
            file.transferTo(newFile);
            //协议 :// ip地址 ：端口号 / 文件目录(/images/2020/03/15/xxx.jpg)
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + directory + newFileName;
            String data[] = new String[1];
            data[0] = url;
            code = 200;
            errno = 0;
            log.info("图片上传，访问URL：" + url);
            return ResultUrl.OK(url,data,errno,code);

        } catch (IOException e) {
            return ResultUrl.OK(null,null,errno,code);
        }

    }

}

